<?php

namespace Common\Taglib;

use Common\Lib\Relation;

class bbs
{
    public function run($opt)
    {
        $order     = empty($opt['order']) ? 'replytime' : trim($opt['order']);
        $field     = trim($opt['field']);
        $num       = empty($opt['num']) ? 10 : intval($opt['num']);
        $tagid     = intval($opt['tagid']);
        $page      = intval($opt['page']);
        $startrow  = intval($opt['startrow']);
        $key       = trim($opt['key']);
        $category1 = intval($opt['category1']);
        $category2 = intval($opt['category2']);
        $uid       = intval($opt['uid']);
        $answernum = intval($opt['answernum']);
        $praisenum = intval($opt['praisenum']);
		$order_array=array('replytime','id','click');
		$orderBy='';
		if (in_array($order, $order_array)){
			$orderBy=$order.' desc';
		}
        $map = array();
        $map = array_merge($map, D('Bbs')->map_audit(3));  // 审核状态条件
        $map = array_merge($map, D('Bbs')->map_category($category1, $category2));  // 分类条件
        if ($uid > 0) {
            $map['uid'] = $uid;   // 发布用户条件
        }
        if (!empty($key)) {
            $map = array_merge($map, D('Bbs')->map_keywords($key));  // 关键词条件
        }
        if (!empty($tagid)) {
            $map = array_merge($map, D('Bbs')->map_tagid($tagid));  // 话题条件
        }
        $ret = D('Bbs')->get_list($map, $page, $orderBy, $num, $startrow);

        $list = $ret['list'];
        $list = Relation::belongsTo($list, 'User', 'uid', 'uid', 'adduser', array(D('User'), 'auto_user_fill'));
        $list = Relation::belongsTo($list, 'User', 'replyuid', 'uid', 'replyuser', array(D('User'), 'auto_user_fill'));
        $list = Relation::hasMany($list, 'BbsTag', 'id', 'bid', 'tags', function ($item){
            foreach ($item as $key => $val) {
                $item[$key] = D('BbsTag')->fill($val);
            }
            return $item;
        });
        $list = Relation::hasMany($list, 'BbsImg', 'id', 'bid', 'imgs', function($item){
            // 获取图片url
            foreach ($item as $key => $val) {
                $imgid = $val['img'];
                $item[$key]['url'] = uploadimgurl($imgid);
            }
            return $item;
        });
        if ($answernum > 0) {
            $list = Relation::hasManyLimit($answernum, $list, 'BbsReply', 'id', 'bid', 'replys', true);
        }
        if ($praisenum > 0) {
            $list = Relation::hasManyLimit($praisenum, $list, 'BbsPraise', 'id', 'bid', 'praise', true);
        }

        $ret['list'] = $list;
//		dump($ret);
        return $ret;
    }
}
?>